import '../public.dart';

class Pagination<R> extends StatefulWidget {
  final Future<List<R>> Function(int page, int pageSize) request;
  final Widget Function(BuildContext context, R item) itemBuilder;
  const Pagination({
    super.key,
    required this.request,
    required this.itemBuilder,
  });

  @override
  State<Pagination> createState() => PaginationState<R>();
}

/// 空数据提示
class _EmptyData extends StatelessWidget {
  final double containerHeight;
  const _EmptyData(this.containerHeight);
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: SizedBox(
        width: ScreenUtil.width,
        height: containerHeight,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(Icons.inbox_outlined, color: Colors.grey[400], size: 40),
            SizedBox(height: 16),
            Text(
              'No Data',
              style: TextStyle(fontSize: 16, color: Colors.grey[400]),
            ),
          ],
        ),
      ),
    );
  }
}

/// 没有更多数据提示
class _NoMoreData extends StatelessWidget {
  const _NoMoreData();
  @override
  Widget build(BuildContext context) {
    return const Padding(
      padding: EdgeInsets.all(16),
      child: Center(
        child: Text('No more data', style: TextStyle(color: Colors.grey)),
      ),
    );
  }
}

/// 全局错误页
class _FullError extends StatelessWidget {
  final String msg;
  final VoidCallback onRetry;
  const _FullError({required this.msg, required this.onRetry});
  @override
  Widget build(BuildContext context) {
    return Center(
      child: BrnAbnormalStateWidget(
        isCenterVertical: true,
        title: msg,
        operateTexts: <String>["pass to retry"],
        operateAreaType: OperateAreaType.textButton,
        action: (index) {
          onRetry();
        },
      ),
    );
  }
}

/// 底部加载更多指示器 / 错误提示
class _LoadMoreFooter extends StatelessWidget {
  final String? error;
  final VoidCallback onRetry;
  const _LoadMoreFooter({this.error, required this.onRetry});
  @override
  Widget build(BuildContext context) {
    if (error != null) {
      return ListTile(
        title: Text(error!, style: const TextStyle(color: Colors.red)),
        trailing: IconButton(
          icon: const Icon(Icons.refresh),
          onPressed: onRetry,
        ),
      );
    }
    return const Padding(
      padding: EdgeInsets.all(16),
      child: Center(child: Text('Loading more...')),
    );
  }
}

class PaginationState<R> extends State<Pagination<R>> {
  late final ListRepository<R> repo;
  late final ScrollController _controller;

  @override
  void initState() {
    super.initState();
    // 使用重构后的 ListRepository 构造方式
    repo = ListRepository(request: widget.request)..refresh(true); // 自动拉首屏
    _controller = ScrollController()..addListener(_onScroll);
  }

  // 暴露刷新方法以允许外部调用
  void refresh(bool? isFirst) {
    repo.refresh(isFirst);
  }

  void _onScroll() {
    // 当滚动到底部时加载更多数据
    if (_controller.position.pixels == _controller.position.maxScrollExtent) {
      if (repo.state.canLoadMore) {
        repo.loadMore();
      }
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: repo,
      builder: (context2, child) {
        final state = repo.state;

        // 初始加载错误状态
        if (state.isInitialError) {
          return _FullError(
            msg: state.error ?? 'Load Failed',
            onRetry: () => repo.refresh(false),
          );
        }

        // 空数据状态（非加载中且无初始错误）
        if (!state.refreshing && !state.isInitialError && state.items.isEmpty) {
          // 获取当前元素高度
          final renderBox = context2.findRenderObject() as RenderBox?;
          final itemHeight = renderBox?.size.height ?? 200;
          return RefreshIndicator(
            child: _EmptyData(itemHeight),
            onRefresh: () => repo.refresh(true),
          );
        }

        // 下拉刷新中显示加载指示器
        if (state.refreshing && state.items.isEmpty) {
          return const Center(child: CircularProgressIndicator());
        }

        return RefreshIndicator(
          onRefresh: () => repo.refresh(false),
          child: ListView.builder(
            controller: _controller,
            physics: const AlwaysScrollableScrollPhysics(), // 空列表也能下拉刷新
            padding: const EdgeInsets.symmetric(vertical: 8),
            itemCount: _calculateItemCount(state),
            itemBuilder: (context, index) {
              // 最后一项为底部状态指示器
              if (index >= state.items.length) {
                return _buildFooter(state);
              }
              // 渲染列表项
              return widget.itemBuilder(context, state.items[index]);
            },
          ),
        );
      },
    );
  }

  /// 计算列表项总数（数据项 + 底部状态项）
  int _calculateItemCount(PageState<R> state) {
    // 如果有数据且还有更多数据，显示底部加载更多
    if (state.items.isNotEmpty && state.hasMore) {
      return state.items.length + 1;
    }
    // 如果数据为空且不处于加载状态，显示正常项目数量
    return state.items.length;
  }

  /// 构建底部状态指示器
  Widget _buildFooter(PageState<R> state) {
    if (state.refreshing) return const SizedBox.shrink();
    // 如果有错误，显示错误提示
    if (state.hasError && !state.refreshing) {
      return _LoadMoreFooter(error: state.error, onRetry: repo.loadMore);
    }

    // 如果正在加载更多，显示加载指示器
    if (state.loading && !state.refreshing) {
      return _LoadMoreFooter(onRetry: repo.loadMore);
    }

    // 如果没有更多数据，显示"没有更多数据"
    if (!state.hasMore && state.items.isNotEmpty) {
      return const _NoMoreData();
    }

    // 默认返回加载指示器
    return _LoadMoreFooter(onRetry: repo.loadMore);
  }
}
